<?php

require_once (dirname(__FILE__)."/../lib/YopClient.php");
require_once (dirname(__FILE__)."/../lib/YopClient3.php");
require_once (dirname(__FILE__)."/../lib/Util/YopSignUtils.php");
require_once(dirname(__FILE__)."/../conf/conf.php");

function object_array($array) {
    if(is_object($array)) { 
        $array = (array)$array; 
     } if(is_array($array)) { 
         foreach($array as $key=>$value) { 
             $array[$key] = object_array($value); 
             } 
     } 
     return $array; 
}


//支付下单
function pay($order){
    global  $private_key;
    global $yop_public_key;
    global $merchantNo;
    $paymentPlugin = M('Plugin')->where("code='qm' and  type = 'payment' ")->find(); // 找到支付插件的配置
    $config_value = unserialize($paymentPlugin['config_value']); // 配置反序列化

    $merchantNo = trim($config_value['merchantNo']);//商户号
    $yop_public_key  = trim($config_value['yop_public_key']);//公钥
    $private_key = trim($config_value['private_key']);//私钥

    $request = new YopRequest($merchantNo, $private_key, "https://open.yeepay.com/yop-center",$yop_public_key);

    //加入请求参数
    $request->setEncrypt(true);
    $request->setSignRet(true);
    $request->setSignAlg("sha256");
    $request->addParam("requestNo",$order['order_sn']);
    $request->addParam("orderAmount", $order['total_amount']);
    $request->addParam("fundAmount", $order['order_amount']);
	$request->addParam("merchantOrderDate", date("Y-m-d H:i:s", time()));
    $request->addParam("serverCallbackUrl", $_SERVER["REQUEST_SCHEME"].'://'.$_SERVER["SERVER_NAME"].U('Home/Payment/qm_notifyUrl',array('pay_code'=>'qm')));
    $request->addParam("webCallbackUrl", $_SERVER["REQUEST_SCHEME"].'://'.$_SERVER["SERVER_NAME"].U('Mobile/Cart/Cart4',array('order_id'=>$order['order_id'])));
    $request->addParam("mcc", "3101");
    $request->addParam("productCatalog", "3101");
    $request->addParam("productName", "缤贝商品");
    $request->addParam("productDesc", "缤贝商品");
	$request->addParam("ip", $_SERVER["REMOTE_ADDR"]);
    $response = YopClient3::post("/rest/v1.0/payplus/order/consume", $request);

    if($response->validSign==1){
        echo "返回结果签名验证成功!\n</br>";
    }
    //取得返回结果
    $data=object_array($response);

    return $data;
    
 }

 function return_response(){

     //引入解密方法
     include_once "plugins/payment/qm/callback/callback.php";
     //获取数据并解密字符串
     $data = $_REQUEST["response"];

     //调试
    // $data = 'GE6_jThzVHZtRusFqt79YnW69FrDBuzyr4mqhVRGp5GckmZaRNdfnvTYJqKqFU9JmvsenooJIPt4-nmaxEOdcoEVNdS6-V8pv3vmEcb7diPcBCOmAJfJLJOs53t3qZp7-ydTPpU5u3MkKdUc-LdmAAE4387RiDDtD_zTXR-KN-sYe00x9pWwp-Q-8vyRzDovTwLXFfRI7My72ydByQYQezrM30tZcG8iZBu_nQeatxsBklCBxruAZxPGsB6Q5FWp4Fv4SpBoOfwWFJY7yPzsAm_y59eTQY01lYJhMjBk0BpjfuxsgyX8iyCJKiDUXge375zmBbvqUc-irhD1UyKa2A$-8_O8qqYAKOgLTDIGKAzMta_NtvBsKGhk5JMXVtqk-9Qf-K9DBKrsS5GCqXZIEh326OpebMXWDBDDDDHeECUkFHjYZ_alLtZS49Tc061rscBN4s6ZbXyFJvGla3W5CTnAnCyELZ98hGz_-nofTNxF6ZKGzKxUlJ0VZvyLkwGg7ZC4NR0mgWI53jvt9dGh34jI4OmA5ToT8DgYczVRXcfZ5G20u7OdLNaCpgQBHyC9HfmDIk8b4N-XgQeELItxBS0_9Qm3_0hEUwzbM5Bwn3FoPl6ZS7tnEi4eLn6FmbDOfIzss_B3dAjwhmVHNQi-3Qbk8361_FPVUQIpHbpvk2T38bSA2HKs3RGC2eNLK0pC2cXXp2u8j139OEIixaphDWov4DnPkxAsVC0CZsvRr2lK3w5yDbog0Ty3QcoXDwP4KTa0fCWMlIWXnSf1JmW5yKRqWFdny9X6osGTWt82845FAjoutXwQSvujXufFPeMfyyQMBxRKRSJdShu42K4DawwFiYGOOe00rJ7PUwYzZRrbd14mm6YYQ-cQg8Qx2R1q1-7HBCNyLenq0fjzLictObuX9lYbWSqQvcXyX4f6grfS4UTE4QXb_t8BOVh1yXE14oU73dhkdB-fiVBq7TiWtfZ6L6BepO6GCNX5-0O6vTI4B76jUcRB1W8FjSEXNJkMVKbA98AEvqPqG7eRCrhV0osFCrBTywfdkjRNWklRQamrJSkTzyMQoz5ittAimlYB_UcprvilFkpSQQKE1UEvEcPt3dAOaijluvb5yCUF8Nfgib6qL9jRa5Vi2Fn8a1JXhqd3lyxCGiJl-LlgwjXsr73LyNDMyd5HCSHdOQh8Z7mM28FqG1JrutqPNebaZZw6iqt6EKzcJFth0lRxnzu3GTA9-vRJ0nT7HTHBy9BidZj5EA7DmKfWN3XH-JtseAtAoO6ouyKQZ-WK-ituWN0vawTxozorH0ES012PHZ7HxfWUA$AES$SHA256';

//    $fopen = fopen($_SERVER['DOCUMENT_ROOT']."/AsynchronousCallback.txt",'wb');
//    fwrite($fopen,$data);
//    fclose($fopen);
//    die;

     $JsonData = callback($data);
     $rechargeData = json_decode($JsonData, true);

     $notfiyOutput = array();

     if($rechargeData['code'] != 1){
         echo 'ERROR';
         return false;
     }
     $order = M('order')->where(['order_sn' => $rechargeData['requestNo']])->find();


     //file_put_contents('/web/tpshop2/c.html',print_r($data,true),FILE_APPEND);
     //20160316 JSAPI支付情况 去掉订单号后面的十位时间戳
     if(strlen($order['order_sn']) > 18){
         $order['order_sn'] = substr($order['order_sn'],0,18);
     }

     if ($order['pay_status'] != 0){
         echo 'ERROR';
         die;
     }


     //用户在线充值
     if (stripos($order['order_sn'], 'recharge') !== false)
         $order_amount = M('recharge')->where(['order_sn' => $order['order_sn'], 'pay_status' => 0])->value('account');
     else
         $order_amount = M('order')->where(['order_sn'=>$order['order_sn']])->value('order_amount');

     //验证价格
     if((string)$order_amount != (string)($rechargeData['fundAmount']))
         return false; //验证失败
     update_pay_status($order['order_sn'],array('transaction_id'=>$rechargeData['bankOrderId'])); // 修改订单支付状态

     return true;
 }

// if( $array['result'] == NULL)
// {
// 	echo "error:".$array['error'];
//  return;
//}
//else{
// $result= $array['result'] ;
// //var_dump($result);
// die;
//}

?>

